package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.media.recorder.RawAudioRecorder;
import com.stark.speechrec.lib.ShortSpeechRecognizer;
import com.stark.translator.util.LanCodeUtil;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivitySpeechTranslationBinding;
import flc.ast.dialog.LanguageDialog;
import flc.ast.utils.Content;
import flc.ast.utils.PcmToWav;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.apis.base.ShortSpeechRecRet;
import stark.common.base.IReqRetCallback;
import stark.common.basic.media.audio.AudioFormat;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.other.LanCode;
import stark.common.other.ReqManager;
import stark.common.other.bean.TranslateRet;

public class SpeechTranslationActivity extends BaseAc<ActivitySpeechTranslationBinding> {

    private ShortSpeechRecognizer mSpeechRecognizer = ShortSpeechRecognizer.getInstance();
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private AudioPlayerImpl mAudioPlayer;
    private boolean mInitTime;

    private Runnable taskUpdateTime = new Runnable() {
        @Override
        public void run() {
            long duration = mSpeechRecognizer.getRecDuration();
            mDataBinding.tvTime.setText(TimeUtils.millis2String(duration, "mm:ss"));
            mHandler.postDelayed(this, 0);
        }
    };
    private LanCode mCurSelLanCode;
    private static final int GEN_LAN_CODE_COUNT = 3;

    @Override
    protected int onCreate() {
        return R.layout.activity_speech_translation;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSpeechTranslationBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mInitTime = true;
        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.setListener(new IAudioPlayer.IListener() {
            @Override
            public void onUpdatePlayTime(int curPlayTime, int duration) {
                if (mInitTime) {
                    mDataBinding.sbPlay.setMax(duration);
                    mInitTime = false;
                    mDataBinding.tvPlayRightText.setText(TimeUtils.millis2String(duration, "mm:ss"));
                }
                mDataBinding.sbPlay.setProgress(curPlayTime);
                mDataBinding.tvPlayLeftText.setText(TimeUtils.millis2String(curPlayTime, "mm:ss"));
                if (curPlayTime + 1000 >= duration) {
                    mDataBinding.sbPlay.setProgress(duration);
                    mDataBinding.tvPlayLeftText.setText(TimeUtils.millis2String(duration, "mm:ss"));
                }
            }

            @Override
            public void onPlayChange(boolean isPlaying) {
                if (isPlaying) {
                    mDataBinding.ivPlay.setImageResource(R.drawable.abofangzhong);
                } else {
                    mDataBinding.ivPlay.setImageResource(R.drawable.azantinz);
                }
            }
        });
        mDataBinding.sbPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mAudioPlayer.seekTo(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mSpeechRecognizer.setStateListener(new RawAudioRecorder.IStateListener() {
            @Override
            public void onStateChanged(@NonNull RawAudioRecorder.State oldState, @NonNull RawAudioRecorder.State newState) {
                if (isFinishing() || isDestroyed()) return;

                if (newState == RawAudioRecorder.State.IDLE) {
                    //变为了空闲，说明录制结束，则开始识别
                    mDataBinding.ivRecord.setImageResource(R.drawable.aluyin);
                    mDataBinding.llPlay.setVisibility(View.VISIBLE);
                    mDataBinding.tvTime.setVisibility(View.GONE);
                    mHandler.removeCallbacks(taskUpdateTime);
                    startRecognize();
                    convert2Wav();
                } else if (newState == RawAudioRecorder.State.REC) {
                    //录制中
                    mDataBinding.ivRecord.setImageResource(R.drawable.azhengzailuy);
                    mDataBinding.tvTime.setVisibility(View.VISIBLE);
                    mDataBinding.llPlay.setVisibility(View.GONE);
                    mDataBinding.etRecResult.setText(getString(R.string.record_ing));
                }
            }
        });
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.ivRecord.setOnClickListener(this);
        mDataBinding.ivTranslation.setOnClickListener(this);
        mDataBinding.tvResultLan.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlay://播放
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                } else {
                    mAudioPlayer.resume();
                }
                break;
            case R.id.ivRecord://录音
                RawAudioRecorder.State state = mSpeechRecognizer.getState();
                if (state == RawAudioRecorder.State.IDLE) {
                    startRecAudio();
                } else {
                    stopRecAudio();
                }
                break;
            case R.id.ivTranslation://翻译文本
                translate();
                break;
            case R.id.tvResultLan://切换语言
                showLanguageDialog();
                break;
        }
    }

    @Override
    protected void initData() {
        List<LanCode> lanCodeList = LanCodeUtil.extractFromGeneralLanCodeList(GEN_LAN_CODE_COUNT);
        if (lanCodeList != null && lanCodeList.size() > 0) {
            mCurSelLanCode = lanCodeList.get(0);
            mDataBinding.tvResultLan.setText(mCurSelLanCode.getName());
        }
    }

    private void startRecAudio() {
        StkPermissionHelper.permission(Manifest.permission.RECORD_AUDIO).reqPermissionDesc(getString(R.string.record_audio_req_tips)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                String recFilePath = FileUtil.generateFilePathByName("stt", "stt.pcm");
                mSpeechRecognizer.startRecAudio(recFilePath);
                mHandler.post(taskUpdateTime);
            }
        }).request();
    }

    private void stopRecAudio() {
        mSpeechRecognizer.stopRecAudio();
    }

    //转换格式
    private void convert2Wav() {
        showDialog(getString(R.string.loading));
        String originalPath = FileUtil.generateFilePath(Content.Temp, AudioFormat.WAV.getSuffix());
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                List<String> fileList = new ArrayList<>();
                fileList.add(mSpeechRecognizer.getRecFilePath());
                boolean result = PcmToWav.mergePCMFilesToWAVFile(fileList, originalPath);
                emitter.onNext(result);
            }

            @Override
            public void accept(Boolean result) {
                dismissDialog();
                if (result) {
                    mAudioPlayer.play(originalPath);
                }
            }
        });
    }


    private void startRecognize() {
        showDialog(getString(R.string.rec_ing));
        mSpeechRecognizer.startRecognize(this, mSpeechRecognizer.getRecFilePath(), new IReqRetCallback<ShortSpeechRecRet>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable ShortSpeechRecRet result) {
                dismissDialog();
                if (result == null || result.result == null) {
                    ToastUtils.showShort(msg);
                    return;
                }
                StringBuilder builder = new StringBuilder();
                for (String str : result.result) {
                    builder.append(str);
                }
                mDataBinding.etRecResult.setText(builder.toString());
            }
        });
    }

    private void translate() {
        String content = mDataBinding.etRecResult.getText().toString();
        if (TextUtils.isEmpty(content) || mCurSelLanCode == null) {
            return;
        }

        showDialog(getString(R.string.translating));
        ReqManager.getInstance().translate(this, content, LanCode.AUTO, mCurSelLanCode, new IReqRetCallback<TranslateRet>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable TranslateRet result) {
                dismissDialog();
                if (result != null) {
                    //将本次翻译成功的文本保存起来
                    mDataBinding.etTransResult.setText(result.getResult());
                } else {
                    ToastUtils.showShort(msg);
                }
            }
        });
    }

    private void showLanguageDialog() {
        LanguageDialog dialog = new LanguageDialog(mContext);
        dialog.mCurSelLanCode = mCurSelLanCode;
        dialog.setListener(new LanguageDialog.Ilistener() {
            @Override
            public void clickSelLan(LanCode lanCode) {
                mCurSelLanCode = lanCode;
                mDataBinding.tvResultLan.setText(lanCode.getName());
                translate();
            }
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSpeechRecognizer.stopRecAudio();
        mHandler.removeCallbacksAndMessages(null);
    }

}